import React from 'react';

// 假设的数据源
const DataSource = {
  comments: [
    { id: 1, text: '评论1' },
    { id: 2, text: '评论2' },
  ],
  blogPosts: {
    1: '这是博客文章1的内容',
    2: '这是博客文章2的内容',
  },
  
  getComments() {
    return this.comments;
  },
  
  getBlogPost(id) {
    return this.blogPosts[id];
  },
  
  addChangeListener(callback) {
    // 实际应用中会在数据变化时调用回调
    // 这里简化处理
  },
  
  removeChangeListener(callback) {
    // 实际应用中会移除监听器
    // 这里简化处理
  }
};

// 高阶组件
function withSubscription(WrappedComponent, selectData) {
  class WithSubscription extends React.Component {
    constructor(props) {
      //console.log('props',props)
      super(props);
      this.handleChange = this.handleChange.bind(this);
      this.state = {
        data: selectData(DataSource, props)
      };
    }

    componentDidMount() {
      DataSource.addChangeListener(this.handleChange);
    }

    componentWillUnmount() {
      DataSource.removeChangeListener(this.handleChange);
    }

    handleChange() {
      this.setState({
        data: selectData(DataSource, this.props)
      });
    }

    render() {
      //console.log('this.state.data',this.state.data)
      //console.log('this.props',this.props)
      WrappedComponent.staticMethod = function() {}
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
  WithSubscription.staticMethod = function() {};
  WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
  return WithSubscription;
}

function getDisplayName(WrappedComponent) {
  //console.log('WrappedComponent.displayName',WrappedComponent.displayName)
  //console.log('WrappedComponent.name',WrappedComponent.name)
  return WrappedComponent.displayName || WrappedComponent.name || 'component';
}

// 被包装组件 - 评论列表
const Comment = ({ comment }) => (
  <div style={{ margin: '8px', padding: '8px', border: '1px solid #ddd' }}>
    <p>{comment.text}</p>
  </div>
);

const CommentList = ({ data }) => (
  <div>
    <h3>评论列表</h3>
    {
      data.map(comment => (
        <Comment comment={comment} key={comment.id} />
      ))
    }
  </div>
);

// 被包装组件 - 博客文章
const TextBlock = ({ text }) => (
  <div style={{ margin: '16px', padding: '16px', background: '#f9f9f9' }}>
    <p>{text}</p>
  </div>
);

const BlogPost = ({ data }) => (
  <div>
    <h3>博客文章</h3>
    <TextBlock text={data} />
  </div>
);

// 使用高阶组件创建增强组件
const CommentListWithSubscription = withSubscription(
  CommentList,
  (DataSource) => DataSource.getComments()
);


//console.log('---',CommentListWithSubscription.staticMethod === undefined)

const BlogPostWithSubscription = withSubscription(
  BlogPost,
  (DataSource, props) => DataSource.getBlogPost(props.id)
);

// 应用根组件
const Hoc = () => (
  <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
    <h1>高阶组件示例</h1>
    <CommentListWithSubscription />
    <BlogPostWithSubscription id={1} />
  </div>
);


export default Hoc